<?php

namespace App\Console\Commands\Clickhouse;

use App\Models\Clickhouse\Guanyuan\GyShopSignCHModel;
use App\Remote\Guanyuan\GuanyuanRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class SysGyShopSignCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clickhouse:sys:sysGyShopSign';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步 签约信息表ETL -> clickhouse';

    public int $id;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        try {

            ini_set('memory_limit', '2G');
            $fields = [
                "region",
                "contractNumber",
                "provincialCorrection",
                "urbanCorrection",
                "customerName",
                "customerMobilePhone",
                "resourceManager",
                "channelCategory",
                "customerSource",
                "signingTime",
                "paybackTime",
                "franchiseFee",
                "technologyTransferFee",
                "royalty",
                "decorationDeposit",
                "securityDeposit",
                "total",
                "signingManager",
                "numberOfContractStores",
                "contractType",
                "remark",
                "cueAcquisitionTime",
                "leadTransferTime",
                "refundMark",
                "interactiveMode",
                "idNumber",
                "provincesAndAutonomousRegions",
                "provincialCollaborator",
                "operationalCollaborator",
                "contractPolicy",
                "discountAmount",
                "occupation",
                "type",
                "theNameOfTheMerchant",
                "employeeStatus",
                "dateOfEntry",
                "group",
                "cityLevel",
                "brandRoyalty",
                "operatingSubsidyAmount",
                "subsidyInKind",
                "nameOfTheSignatory",
                "theSignatoryDepartment",
                "joiningMode",
                "keyCity"
            ];

            $this->id = 0;

            $data = GuanyuanRemote::sourceData(
                's638bd087fb3d44e39cf62b2',
                't4d406b9476d940f2a92c3bc',
                [],
                0
            );

            $this->getOutput()->info("数据量 :  " . count($data["data"] ?? []));
            if ($data["data"]) {
                $batchInsert = [];
                collect($data["data"])->each(function ($row) use (
                    $fields,
                    &$batchInsert
                ) {
                    $this->id = $this->id + 1;
                    $insert   = [
                        "id"        => $this->id,
                        "createdAt" => time()
                    ];

                    collect($row)->each(function ($value, $key) use ($fields, &$insert, &$batchInsert) {
                        if (isset($fields[$key])) {
                            $insert[$fields[$key]] = $value;
                        } else {
                            return false;
                        }
                    });

                    array_push($batchInsert, $insert);

                });

                if ($batchInsert) {
                    DB::connection("clickhouseDataStatistics")
                      ->statement('TRUNCATE ' . (new GyShopSignCHModel())->getTable());
                    collect($batchInsert)->chunk(500)->each(function (Collection $collection) {
                        GyShopSignCHModel::query()->insert($collection->values()->toArray());
                    });
                }
            }

            logInfo("{$this->description} 成功", collect([]), true, false);

        } catch (\Exception $exception) {
            logException("{$this->description} 失败", $exception, null, true, true);
        }
        return 0;
    }
}
